<template>
  <div class="slider" ref="slider">
		<!-- 
		//img snap参数地址  
		https://ustbhuangyi.github.io/better-scroll/doc/zh-hans/options-advanced.html#snap 
    //参数地址 博客
    https://blog.csdn.net/qq_36416878/article/details/80457378
    //轮播图插件最新的写法 
    https://github.com/ustbhuangyi/better-scroll/blob/master/example/components/slide/slide.vue 
		-->
    <div class="slider-group" ref="sliderGroup">
    	<slot></slot>
    </div>
		<!-- dots -->
    <div class="dots">
    	  <span class="dot" 
					:class="{active: currentPageIndex === index }" 
					v-for="(item, index) in this.dots"  
					:key="index">
    		</span>
    </div>
  </div>
</template>

<script>
import {addClass} from 'common/js/dom'
import BScroll from 'better-scroll'
const COMPONENT_NAME = 'slide'
export default {
  name: COMPONENT_NAME,  
    data() {
      return {
        dots: [],
        currentPageIndex: 0
      }
    },
  props:{
    loop:{  // 循环轮播   
      type:Boolean,
      default:true
    },
    autoPlay:{//自动轮播
      type:Boolean,
      default:true
    },
    interval:{//轮播间隔
      type:Number,
      default:4000
    },
    showDot: { // 滚动点
        type: Boolean,
        default: true
      },
      click: {//点击
        type: Boolean,
        default: true
      },
      threshold: { //滑动的距离  阀值
        type: Number,
        default: 0.3
      },
      speed: { //滚动速度
        type: Number,
        default: 1200
      },
      pageTurn:{ //左右箭头  import SlideRender from 'example/page-render/slide-render.vue' @turnToPrevFun()

      }
  },
 mounted() {
      this.update()
      window.addEventListener('resize', () => { //监听改变窗口事件
        if (!this.slider || !this.slider.enabled) {
          return
        }
        clearTimeout(this.resizeTimer)
        this.resizeTimer = setTimeout(() => {
          if (this.slider.isInTransition) {
            this._onScrollEnd()
          } else {
            if (this.autoPlay) {
              this._play()
            }
          }
          this.refresh()
        }, 60)
      })
    },
    activated() {
      if (!this.slider) {
        return
      }
      this.slider.enable()
      let pageIndex = this.slider.getCurrentPage().pageX
      this.slider.goToPage(pageIndex, 0, 0)
      this.currentPageIndex = pageIndex
      if (this.autoPlay) {
        this._play()
      }
    },
    deactivated() { //离开页面清除timer
      this.slider.disable()
      clearTimeout(this.timer)
    },
    beforeDestroy() {
      this.slider.disable()
      clearTimeout(this.timer)
    },
  methods: {
    update() { //当DOM发生改变的时候 调用
        if (this.slider) { //存在事件就销毁
          this.slide.destroy()
        }
        this.$nextTick(() => {
          this.init()
        })
      },
      refresh() {
        this._setSliderWidth(true)
        this.slider.refresh()
      },
      prev() {
        this.slider.prev()
      },
      next() {
        this.slider.next()
      },
       init() {
        clearTimeout(this.timer)
        this.currentPageIndex = 0
        this._setSliderWidth()
        if (this.showDot) {
          this._initDots() //循环小圆点事件
        }
        this._initSlider() //轮播图loop事件
        if (this.autoPlay) {
          this._play()   //触发下张轮播图事件
        }
      },

    _setSliderWidth(isResize){//计算轮播图宽度 给轮播图添加样式
        this.children=this.$refs.sliderGroup.children;//获取轮播图的子元素数组长度
        // console.log(this.children.length)
        let width=0;
        let sliderWidth=this.$refs.slider.clientWidth//获取轮播图祖父元素的宽度=》只有子元素总长度大于父元素长度才可以滚动
        for (let index = 0; index < this.children.length; index++) {
             const child = this.children[index];
             addClass(child,"slider-item")//动态添加css样式
             child.style.width=sliderWidth+"px"//设置子元素的宽度是父元素的100%
             width+=sliderWidth//获取总长度
        }
       if (this.loop && !isResize) {
          width += 2 * sliderWidth
        }
        this.$refs.sliderGroup.style.width=width+"px" //获取图片盒子的总宽度
    },
		
    _initSlider(){ //启动better-scroll插件 
        this.slider=new BScroll(this.$refs.slider,{
          scrollX: true,
          scrollY: false,
          momentum: false,//当快速在屏幕上滑动一段距离的时候，会根据滑动的距离和时间计算出动量，并生成滚动动画。设置为 true 则开启动画。
          snap: {
            loop: this.loop,//是否开启无缝轮播
            threshold: this.threshold,//滑动的距离
            speed: this.speed,//滚动速度
            interval:4000//轮播间隔
          },
          bounce: false,//当滚动超过边缘的时候会有一小段回弹动画。设置为 true 则开启
          stopPropagation: true,
          click: this.click,
          pageTurn:true
        }),
        this.slider.on('scrollEnd', () => { //滚动完毕触发事件index 
          let pageIndex = this.slider.getCurrentPage().pageX
          this.currentPageIndex = pageIndex
          if (this.autoPlay) { //无线滚动
            //  clearTimeout(this.timer)
             this._play()
          }
        })

        this.slider.on('touchEnd', () => {
          if (this.autoPlay) {
            this._play()
          }
        })
        this.slider.on('beforeScrollStart', () => {
          if (this.autoPlay) {
            clearTimeout(this.timer)
          }
        })
    },
      _initDots() {//循环小圆点事件
        this.dots = new Array(this.children.length)
      },
      _play() { //触发下张轮播图事件
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.slider.next()
        }, this.interval)
      }


  },
    watch: {
      loop() {
        this.update()
      },
      autoPlay() {
        this.update()
      },
      speed() {
        this.update()
      },
      threshold() {
        this.update()
      }
}}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~common/stylus/variable"

  .slider
    min-height: 1px
    .slider-group
      position: relative
      overflow: hidden
      white-space: nowrap
      .slider-item
        float: left
        box-sizing: border-box
        overflow: hidden
        text-align: center
        a
          display: block
          width: 100%
          overflow: hidden
          text-decoration: none
        img
          display: block
          width: 100%
    .dots
      position: absolute
      right: 0
      left: 0
      bottom: 12px
      text-align: center
      font-size: 0
      .dot
        display: inline-block
        margin: 0 4px
        width: 8px
        height: 8px
        border-radius: 50%
        background: $color-text-l
        &.active
          width: 20px
          border-radius: 5px
          background: $color-text-ll
</style>

